import React from 'react'
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';
import {Popover,Tools,DatePicker,Flex,ActionSheet,WhiteSpace,List,Checkbox,Icon ,Button,SearchBar } from 'weaver-mobile';
import {getNow} from '../../../util/common'
import {Route, withRouter } from 'react-router-dom';
import { RouteLayout,ListPage,SearchAdvanced } from 'weaver-mobile-page';
// import TypeModal from './uiComponents/TypeModal';
const getLabel = Tools.getLabel;
const templates = ListPage.templates;

const tpks = Object.keys(templates);

const mobileshowtemplate = {};
tpks.forEach((theme, index) => {
  mobileshowtemplate[`tp_${index}`] = {
    theme,
    dataKeys: theme === 'avatar' ? ['name', 'url', 'title', 'des', 'id', 'time'] : ['title', 'user', 'time', 'des', 'id'],
  };
});

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@inject ('accountBookStore')
@observer
class AccountBook extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            modal1: false,
            checked:[],
            isReimbursement: false, //报销  未报销
            isSelect:false, //是否点击  选择   --- 取消全选
            onRowSelect:[]  //是否选中 行
        };

        const {accountBookStore} = this.props;
        const {setDateParams,getBaseRoute} = accountBookStore;

        let now = getNow();
        setDateParams({
            year:now.year,
            month:now._month
        });
        
        //获取基础路由
        getBaseRoute(this)
    }

    static defaultProps = {
        prefixCls:"fna-accountBook"
    }

    componentWillMount() {
        // const { selectLinkage,options,selectLinkageDatas } = this.props.accountBookStore;
        // selectLinkage.setState({ options, selectLinkageDatas });
    }    

    componentDidMount() {
        const {accountBookStore} = this.props;
        const {initData,selectLinkage,options,selectLinkageDatas} = accountBookStore;
        initData();
        // selectLinkage.setState({ options, selectLinkageDatas });
        
    }

    render() {
        const { accountBookStore,prefixCls,history } = this.props;
        const { dateParams,rememberGroup,routeData,mark,visible_typeModal,typeItem,typeMark,resetType,
            rememberList,rememberChecked,selectLinkage,baseRoute,search,remindList } = accountBookStore;

        return (
            <div className={`${prefixCls}`}>
                <div className={`${prefixCls}-head`}>
                    <div className={`${prefixCls}-head-data`}>  
                        <DatePicker
                            mode="month"
                            onChange={this.getTime}
                        >
                            <span>{dateParams.year}年{dateParams.month}月<Icon type={'down'} size={'xxs'} /></span>
                        </DatePicker>      
                    </div>

                    <Flex className={`${prefixCls}-head-flex`}>
                        <Flex.Item onClick={()=>{this.changeReimbursement('0')}}>
                            <div>未报销</div>
                            <div className="borderRight-line">￥2000.00</div>
                            {!this.state.isReimbursement ? <div className="bg-sanjiaoUP"></div> : <div></div>}
                        </Flex.Item>
                        <Flex.Item onClick={()=>{this.changeReimbursement('1')}}>
                            <div>已报销</div>
                            <div>￥1392.00</div>
                            {this.state.isReimbursement ? <div className="bg-sanjiaoUP"></div> : <div></div>}
                        </Flex.Item>
                    </Flex>
                </div>

                
                <SearchBar
                    className="search-select"
                    placeholder="Search"
                    showExtraButton
                    extraButton={[{ key: 'advanced', show: <Icon key="filter-o" type="filter-o" /> }]}
                    onExtraButtonClick={(key) => history.push(search.path) }
                    // value={'11111111'}
                />

                <SearchAdvanced
                    store={search}
                />

                
                
                {this.state.isReimbursement ? 
                    <div className="accountBook-flex">
                        <Flex className={'fna-flex-img fna-flex-img-03'}>
                            {rememberGroup.map( item => {
                                let _key = item.key;
                                let string = toJS(item).style;
                                // var str = "toJS(item).style";
                                let _style = eval("("+string+")");
                                
                                let _class = (mark[_key] == '2') ? 'sanjiao_down' : ( mark[_key] == '1' ? 'sanjiao_up' : 'sanjiao_none');
                            

                                let conment = [];
                                {
                                    conment = [
                                            <Flex.Item key={_key}  className={`fna-flex-img-item`} style={{position:'relative'}} onClick={()=>{this.onClick({[_key]: (parseInt(mark[_key])+1)%3})}}>
                                                {_class == 'sanjiao_none' && <div style={_style} className={`fna-flex-img-item-text unActive`} >{item.title}</div>}
                                                {_class !== 'sanjiao_none' && <div className={`fna-flex-img-item-text active`} >{item.title}<span className={`${_class}`}></span></div>}
                                            </Flex.Item>
                                        ]
                                }
                                
                                return conment;
                            })}
                        </Flex>
                        
                        
                        {/* <TypeModal 
                            visible={visible_typeModal} 
                            data={typeItem} 
                            typeMark={typeMark} 
                            handleType={this.handleType} 
                            resetType={resetType} 
                            click={this.onClick.bind(this,{type:(mark['type']=='2') ? 1 : 2})}
                        /> */}
                        
                    </div>
                    :
                    <div className={`${prefixCls}-select`}>
                        {this.state.isSelect ? 
                            <div className={"accountBook-noSelect"}>
                                <span>共<span>1</span>条</span><i>合计：</i><b>CNY</b><em>1392.00</em>
                                <div onClick={()=>{this.setState({isSelect : false})}}>取消选择</div>
                            </div> 
                            : 
                            <div className={"accountBook-isSelect"} onClick={()=>{this.setState({isSelect : true})}}>选择</div>
                        } 
                    </div>
                }

                <ListPage.Normal
                    className={this.state.isSelect ? 'fna-home-listPage fna-accountBook-listPage' : 'fna-home-listPage'}
                    showCheck={this.state.isSelect}
                    multipleCheck={false}
                    withSwipeAction={true}
                    template={this.getTemplate()}
                    store={remindList}
                    multipleCheck
                    onRowClick={(v)=>console.log('点击行',v)}
                    onRowSelect={(v)=>this.setState({onRowSelect:v})}
                    swipeActionProps={{
                        style:{ backgroundColor: 'gray' },
                        autoClose:true,
                        right:[{
                            text: '删除',
                            onPress: () => console.log('删除'),
                            style: { backgroundColor: '#F4333C', color: 'white' },
                        }]
                        
                    }}
                    
                />

                <div className={`${prefixCls}-footer`}>
                    {this.state.isReimbursement ?  
                        <Button type="primary"  style={{'border':0}} onClick={this.handleSubmit}>记一笔</Button>
                        :
                        this.state.isSelect ?  
                            <div className="isReimbursement-isSelect-btn">
                                {remindList.isSelectedAll ? <div onClick={()=>{remindList.selectNone();this.setState({onRowSelect:[]})}}><Icon type="check-circle" color={'#55b1f9'} size={'xs'}/>{getLabel('387379','取消全选')}</div> : <div onClick={()=>{remindList.selectAll()}}><Icon type="uncheck" color="#ccc" size={'xs'}/>{getLabel('556','全选')}</div>}
                                <Button type="primary"  style={{'border':0}} onClick={this.handleSubmit}>记一笔</Button>
                                <Button type="primary"  style={{'border':0}} disabled={remindList.isSelectedAll == true ? false : (this.state.onRowSelect.length > 0 ? false : true)}  onClick={this.showReimbursementType}>发起报销</Button>
                            </div>
                            :
                            <div className="isReimbursement-btn">
                                <Button type="primary"  style={{'border':0}} onClick={this.handleSubmit}>记一笔</Button>
                                <Button type="primary"  style={{'border':0}} disabled={true}  onClick={this.showReimbursementType}>发起报销</Button>
                            </div>
                    }
                </div>
               

                {/* 路由层 */}
                <div>
                   
                </div>
            </div>
        )
    }

    getTime = (value) =>{
        const {accountBookStore} = this.props;
        const {setDateParams} = accountBookStore;
        let y = value.split('-')[0];
        let _m = value.split('-')[1];
        let m = _m.charAt(0) == '0' ? _m.charAt(1) : _m;
        console.log('m',m)
        setDateParams({
            year:y,
            month:m
        })
    }

    //onChange
    onChange = (v) =>{
        const {accountBookStore} = this.props;
        const {setRememberChecked,rememberChecked} = accountBookStore;
        const {dataSeed,checked} = v.target;
        setRememberChecked({
            [dataSeed]:checked
        })
        
        
    }

    //showMonth
    showReimbursementType = () =>{
        const allMonth = [
            {content: '费用报销'},{content: '财务报销'},{content: '取消'},
        ];
        ActionSheet.showActionSheetWithOptions({
            options: allMonth,
            cancelButtonIndex: allMonth.length - 1,
            // destructiveButtonIndex: BUTTONS.length - 2,
            // title: '请选择月份',
            // message: '请选择月份',
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        },  
        (buttonIndex) => {
            const {accountBookStore} = this.props;
            const {setDateParams} = accountBookStore;
            if(buttonIndex != allMonth.length - 1){
                console.log('buttonIndex',buttonIndex,'0:费用报销-------1：财务报销')
            }
               
        });       
    }

    onClick = (value) =>{
        const {accountBookStore} = this.props;
        const {setMark}  = accountBookStore;
        
        setMark(value);
        
        //根据筛选条件搜搜
        const {mark,typeMark}  = accountBookStore;
        //发起请求
        
       
        
    }

    //搜索
    doSerch = () =>{
        const {accountBookStore} = this.props;
        const {mark,typeMark}  = accountBookStore;
        //请求

    }

    //记一笔
    handleSubmit = () =>{
        const {accountBookStore} = this.props;
        const {rememberChecked}  = accountBookStore;
        console.log('rememberChecked',rememberChecked)
    }

    //报销 切换
    changeReimbursement = (value) =>{
        let _isReimbursement = value == '1' ? true : false;

        this.setState({
            isReimbursement: _isReimbursement
        })
    }

    //获取模板  报销流程
    getTemplate = (template) => {
        const {prefixCls} = this.props;
        const newTemplate = {
            default: [
                {
                    key: 'col1',
                    // style: { flex: '0 0 auto'},
                    render: (data) => {
                        let {icon,imgSrc} = data;
                        return(
                            <div className={`fna-home-template`}>
                                <div className={`fna-home-template-left`}>
                                    <div><Icon type={'iphone'} /></div>
                                    <div className={'word-fontSize-12'}>{data.title}</div>
                                </div>
                                <div className={`fna-home-template-middle`}><img src={JSON.parse(imgSrc).splitLine} /></div>
                                <div className={`fna-home-template-right`}>
                                    {this.getTypeLayout(data)}
                                </div>
                            </div>
                            
                        )
                    }
                },  

                    
            ],
        };

        return newTemplate;
    }

    //记一笔类型 对应布局
    getTypeLayout = (data) =>{
        const { homeStore,prefixCls } = this.props;
        let layout = [];
        if(data.type == 'foodSubsidy'){
            layout = [
                <div className={`fna-home-foodSubsidy`} key={data.id}>
                    <div>
                        <p>{data.user}</p>
                        <p><span><Icon type={'icon-shizhong-fill'} /></span><span className="word-fontSize-12">{data.time}</span></p>
                    </div>
                    <div>&nbsp;</div>
                    <div><span style={{color:'#868686'}}>CNY</span>{data.money}</div>
                </div>
            ] 
        }else if(data.type == 'stay'){
            layout = [
                <div className={`fna-home-stay`} key={data.id}>
                    <div>
                        {data.endPlace ? <p>{data.startPlace}<img src={JSON.parse(data.imgSrc).arrive} className={'arrive'}/>{data.endPlace}</p> : <p dangerouslySetInnerHTML={{__html: data.startPlace}} />}
                        <p><span>{data.user}</span></p>
                    </div>
                    <div className='stay-two'><span><Icon type={'icon-shizhong-fill'} /></span><span>{data.time}</span></div>
                    <div><span style={{color:'#868686'}}>CNY</span>{data.money}</div>
                </div>
            ] 
        }else if(data.type == 'traffic'){
            layout = [
                <div className={`fna-home-traffic`} key={data.id}>
                    <div>
                        <p><span dangerouslySetInnerHTML={{__html: data.place}}></span><img src={JSON.parse(data.imgSrc).arrive} className={'arrive'}/>{data.endPlace}</p>
                        <p><span>{data.user}</span></p>
                    </div>
                    <div className='stay-two'>
                        <span><Icon type={'icon-shizhong-fill'} /></span><span>{data.time}</span>
                        <span className='upTime'>上</span><span className='detailTime'>{data.startTime}</span>
                        <span className='downTime'>下</span><span className='detailTime'>{data.endTime}</span>
                    </div>
                    <div><span style={{color:'#868686'}}>CNY</span>{data.money}</div>
                </div>
            ] 
        }else {
            layout = [
                <div key={data.id}>
                    <div>22222222222</div>
                    <div>22223322</div>
                </div>
            ] 
        }

        return layout;
    }
    

    
    

}

export default AccountBook;